package com.wally.netty.client;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class EchoClientHandler extends ChannelHandlerAdapter {

	private int counter;
	
	private static final String ECHO_REQ = "Hi, Welcome to Netty 5 .$_";
	
	public EchoClientHandler() {
		
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) {// 当客户端和服务端TCP链路建立成功之后，Netty的NIO线程会调用channelAction方法，
		// 发送查询时间的指令给服务端，调用writeAndFlush方法将请求消息发送给服务端
		for (int i = 0; i < 10; i++) {
			ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//当服务端返回应答消息时，channelRead方法被调用
		System.out.println("This is : " + ++counter + " times receive server :[" + msg + "]");
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// 当发生异常时，打印异常日志，释放客户端资源
		cause.printStackTrace();
		ctx.close();
	}

}
